<!-- 代码已包含 CSS：使用 SCSS 样式 -->
<template>
  <div class="container">
    <!-- 顶部导航 -->
    <header class="header">
      <div class="header-content">
        <div class="header-left">
          <img :src="logo" alt="Logo">
          <h1>声生知音</h1>
        </div>
        <div class="header-right">
          <button class="return-btn">
            <router-link to="/main">返回主页</router-link>
          </button>
          <div class="avatar" @click.stop="toggleAvatarMenu">
            <img :src="userInfo.avatar || userAvatar" alt="Avatar">
            <span>{{ userInfo.username || '未设置昵称' }}</span>
          </div>
        </div>
      </div>
    </header>
    <!-- 主体内容 -->
    <div class="main-content">
      <!-- 侧边栏 -->
      <aside class="sidebar">
        <div class="sidebar-content">
          <div v-for="(group, index) in menuGroups" :key="index" class="menu-group">
            <div class="menu-title">{{ group.title }}</div>
            <div v-for="item in group.items" :key="item.key" :class="[
              'menu-item',
              {
                'menu-item-active': activeMenu === item.key && !item.type,
                'menu-item-danger': item.type === 'danger'
              }
            ]" @click="handleMenuClick(item.key)">
              {{ item.label }}
            </div>
          </div>
        </div>
      </aside>
      <!-- 主内容区 -->
      <main class="main-area">

        <!-- 个人资料 -->
        <div v-show="activeMenu === 'profile'" class="profile-section">
          <div class="profile-card">
            <h2 class="sectionTitle">基本信息</h2>
            <div class="profile-header">
              <div class="avatar-container" :class="{ 'editable': editMode }" @click="handleAvatarClick">
                <a-avatar :size="120" :src=" previewAvatar|| userInfo.avatar || userAvatar" />
                <div class="avatar-overlay" v-if="editMode">
                  <CameraOutlined class="camera-icon" />
                  <input type="file" ref="fileInput" style="display: none;" accept="image/*"
                    @change="handleFileChange" />
                </div>
              </div>
              <div class="profile-info">
                <div class="profile-title">
                  <h2 class="section-title"></h2>
                  <div class="edit-controls">
                    <EditOutlined v-if="!editMode" class="edit-icon" @click="editMode = true" />
                    <template v-else>
                      <a-button type="text" class="cancel-btn" @click="cancelEdit">取消</a-button>
                      <a-button type="primary" class="save-btn" @click="saveEdit">保存</a-button>
                    </template>
                  </div>
                </div>
                <div class="profile-form">
                  <div class="form-item">
                    <span class="form-label">昵称</span>
                    <div class="input-wrapper">
                      <a-input
                        v-model:value="userInfo.username"
                        :disabled="!editMode"
                        :status="usernameError ? 'error' : ''"
                        @change="validateUsername"
                        @focus="showTooltip = true"
                        @blur="showTooltip = false"
                        placeholder="请输入昵称"
                        :maxlength="10"
                      />
                      <div class="tooltip" :class="{ 'error': usernameError, 'show': showTooltip || usernameError }">
                        {{ usernameError ? '昵称长度必须在2-8个字符之间' : '请输入2-8个字符的昵称' }}
                      </div>
                    </div>
                  </div>
                  <div class="form-item">
                    <span class="form-label">性别</span>
                    <a-radio-group v-model:value="userInfo.sex" :disabled="!editMode">
                      <a-radio value="男">男</a-radio>
                      <a-radio value="女">女</a-radio>
                    </a-radio-group>
                  </div>
                  <div class="form-item">
                    <span class="form-label">职业</span>
                    <a-select v-model:value="userInfo.occupation" style="width: 200px" :disabled="!editMode">
                      <a-select-option value="developer">学生</a-select-option>
                      <a-select-option value="designer">教师</a-select-option>
                      <!-- <a-select-option value="pm"></a-select-option> -->
                    </a-select>
                  </div>
                  <div class="form-item bio-item">
                    <span class="form-label">个人简介</span>
                    <a-textarea v-model:value="userInfo.introduction" :disabled="!editMode"
                      :auto-size="{ minRows: 3, maxRows: 6 }" placeholder="请输入您的个人简介" class="bio-input" />
                  </div>

                </div>
              </div>
            </div>
          </div>
          <div class="profile-card">
            <h2 class="section-title">绑定手机号</h2>
            <div class="contact-info">
              <span class="form-label">手机号</span>
              <span>138****8888</span>
              <button class="change-phone-btn" @click="handleChangePhone">
                更换手机号
              </button>
              <!-- 更换手机号弹窗 -->
              <a-modal v-model:open="showPhoneModal" title="更换手机号" @ok="submitPhoneChange" okText="确认" cancelText="取消"
                :style="{ top: '200px' }">
                <a-form :model="phoneForm" layout="vertical">
                  <a-form-item label="当前手机号">
                    <a-input v-model:value="phoneForm.oldPhone" disabled />
                  </a-form-item>
                  <a-form-item label="新手机号">
                    <a-input v-model:value="phoneForm.newPhone" placeholder="请输入新手机号" />
                  </a-form-item>
                  <a-form-item label="验证码">
                    <div style="display: flex; gap: 8px;">
                      <a-input v-model:value="phoneForm.code" placeholder="请输入验证码" style="flex: 1" />
                      <a-button :disabled="countdown > 0" @click="sendVerificationCode">
                        {{ countdown > 0 ? `${countdown}s` : '获取验证码' }}
                      </a-button>
                    </div>
                  </a-form-item>
                </a-form>
              </a-modal>
            </div>
          </div>
          <!-- 认证 -->
          <div class="profile-card">
            <h2 class="section-title">身份认证</h2>
            <div class="auth-info">
              <div class="auth-status">
                <span class="form-label">认证状态</span>
                <span
                  :class="['status-tag', userInfo.isVerified ? 'verified' : 'unverified']">{{ userInfo.isVerified ? '已认证' : '未认证' }}</span>
              </div>
              <template v-if="!userInfo.isVerified">
                <button class="verify-btn" @click="handleVerify">立即认证</button>
                <!-- 认证弹窗 -->
                <a-modal v-model:open="showVerifyModal" title="身份认证" @ok="submitVerify" okText="提交认证" cancelText="取消"
                  :style="{ top: '200px' }">
                  <a-form :model="verifyForm" layout="vertical">
                    <a-form-item label="真实姓名" required>
                      <a-input v-model:value="verifyForm.realName" placeholder="请输入真实姓名" />
                    </a-form-item>
                    <a-form-item label="身份证号" required>
                      <a-input v-model:value="verifyForm.idNumber" placeholder="请输入身份证号" />
                    </a-form-item>
                    <a-form-item label="手机号" required>
                      <a-input v-model:value="verifyForm.phone" placeholder="请输入手机号" />
                    </a-form-item>
                    <a-form-item label="认证说明">
                      <a-textarea v-model:value="verifyForm.description" placeholder="请简要说明认证用途"
                        :auto-size="{ minRows: 3, maxRows: 5 }" />
                    </a-form-item>
                  </a-form>
                </a-modal>
              </template>
              <div v-else class="verify-info">
                <div class="info-item">
                  <span class="info-label">认证时间</span>
                  <span>{{ userInfo.verifyTime || '2024-01-20' }}</span>
                </div>
                <div class="info-item">
                  <span class="info-label">认证用途</span>
                  <span>{{ userInfo.verifyPurpose || '个人使用' }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- 账号设置 -->
        <div v-show="activeMenu === 'settings'" class="security-section">
          <div class="security-card">
            <h2 class="section-title">密码设置</h2>
            <a-form :model="passwordForm" layout="vertical" :rules="passwordRules">
              <a-form-item label="当前密码" name="oldPassword" :rules="[{ required: true, message: '请输入当前密码' }]">
                <a-input-password v-model:value="passwordForm.oldPassword" />
              </a-form-item>
              <a-form-item label="新密码" name="newPassword" :rules="[
                { required: true, message: '请输入新密码' },
                { min: 8, message: '密码长度至少6位' },
                { max: 20, message: '密码长度最多12位' }
              ]">
                <a-input-password v-model:value="passwordForm.newPassword" />
              </a-form-item>
              <a-form-item label="确认新密码" name="confirmPassword" :rules="[
                { validator: validateConfirmPassword }
              ]">
                <a-input-password v-model:value="passwordForm.confirmPassword" />
              </a-form-item>
              <a-form-item>
                <button class="save-btn" @click="savePassword">
                  保存修改
                </button>
              </a-form-item>
            </a-form>
          </div>
        </div>
        <!-- 数据分析 -->
        <div v-show="activeMenu === 'analysis'" class="analysis-section">
          <div class="stats-grid">
            <div v-for="(stat, index) in statistics" :key="index" class="stat-card">
              <div class="stat-label">{{ stat.label }}</div>
              <div class="stat-value">
                {{ animatedValues[index] }}
                <span>{{ stat.unit }}</span>
              </div>
              <div class="stat-growth">
                <ArrowUpOutlined /> +{{ animatedGrowth[index] }}%
              </div>
            </div>
          </div>
          <div class="chart-card trend-card">
            <h2 class="section-title">活动趋势</h2>
            <div ref="trendChart" style="height: 280px"></div>
          </div>
          <div class="charts-grid">
            <div class="chart-card">
              <h2 class="section-title">时段活跃度</h2>
              <div ref="pieChart" style="height: 260px"></div>
            </div>
            <div class="chart-card">
              <h2 class="section-title">功能使用占比</h2>
              <div ref="barChart" style="height: 260px"></div>
            </div>
          </div>
        </div>

        <!-- 内容分布 -->
        <div v-show="activeMenu === 'content'" class="content-section">
          <div class="charts-grid">
            <div class="chart-card">
              <h2 class="section-title">字数分布</h2>
              <div ref="wordCountChart" style="width: 100%; height: 300px; min-width:400px;"></div>
            </div>
            <div class="chart-card">
              <h2 class="section-title">课件时长分布</h2>
              <div ref="durationChart" style="width: 100%; height: 300px; min-width:400px;"></div>
            </div>
            <div class="chart-card">
              <h2 class="section-title">资源使用情况</h2>
              <div ref="resourceChart" style="width: 100%; height: 300px; min-width:400px;"></div>
            </div>
            <div class="chart-card">
              <h2 class="section-title">声音使用比例</h2>
              <div ref="voiceChart" style="width: 100%; height: 300px; min-width:400px;"></div>
            </div>
          </div>
        </div>
        <!-- 使用帮助 -->
        <div v-show="activeMenu === 'help'" class="help-section">
          <div class="help-grid">
            <div v-for="(feature, index) in helpFeatures" :key="index" class="help-card">
              <div class="help-card-header">
                <component :is="feature.icon" class="feature-icon" />
                <h3>{{ feature.title }}</h3>
              </div>
              <div class="help-card-content">
                <div class="feature-intro">
                  <h4>功能介绍</h4>
                  <p>{{ feature.description }}</p>
                </div>
                <div class="feature-steps">
                  <h4>操作步骤</h4>
                  <ol>
                    <li v-for="(step, stepIndex) in feature.steps" :key="stepIndex">
                      {{ step }}
                    </li>
                  </ol>
                </div>
                <div class="feature-faq">
                  <h4>常见问题</h4>
                  <a-collapse v-model:activeKey="feature.activeKeys" class="faq-collapse">
                    <a-collapse-panel v-for="(faq, faqIndex) in feature.faqs" :key="faqIndex" :header="faq.question"
                      @change="(checked) => handleQuestionClick(index, faqIndex, checked)" class="faq-panel">
                      <p class="faq-answer">{{ faq.answer }}</p>
                    </a-collapse-panel>
                  </a-collapse>
                </div>
              </div>
            </div>
          </div>
        </div>
      </main>
    </div>
  </div>
</template>
<script setup>
  import { ref, onMounted, computed, onUnmounted, nextTick, watch } from 'vue';
  import { CameraOutlined, ArrowUpOutlined, EditOutlined, SoundOutlined, FileTextOutlined, UserOutlined, SettingOutlined, AudioOutlined } from '@ant-design/icons-vue';
  import { Modal, message } from 'ant-design-vue';
  import { getWordCountConfig, getDurationConfig, getResourceConfig, getVoiceConfig, getTrendConfig, getTimeDistributionConfig, getFunctionUsageConfig, initChart } from '@/utils/charts';
  import logo from '@/assets/images/navLogo.webp';
  import defaultAvatar from '@/assets/svg/default-avatar.svg';
  import * as echarts from 'echarts';
  import { useUserStore } from '@/stores/userStore';
  import { useRoute, useRouter } from 'vue-router';
  const route = useRoute();
  const router = useRouter();
  const userStore = useUserStore();
  import { getUserInfo, updateUserInfo, updatePassword } from '@/api/UserCenter';

  const activeMenu = ref(route.query.tab || 'profile');// 激活的菜单


  const userAvatar = ref(defaultAvatar);
  const previewAvatar = ref('');
  const fileInput = ref(null);
  const editMode = ref(false);//是否编辑状态
  //基本信息
  const userInfo = ref({
    username: '',
    sex: '',
    occupation: '',
    introduction: '',
    avatar: userAvatar.value,
    avatarFile: null // 添加avatarFile字段用于存储File对象
  });

    const usernameError = ref(false);
    const showTooltip = ref(false);

    const validateUsername = () => {
      const username = userInfo.value.username;
      usernameError.value = !username || username.length < 2 || username.length > 8;
    };
  const originalUserInfo = ref(null);
  //上传头像方法
  const handleAvatarClick = () => {
    if (editMode.value) {
      fileInput.value.click();
    }
  };
  const handleFileChange = (event) => {
    const file = event.target.files[0];
    if (file) {
      // 检查是否为图片文件
      if (!file.type.startsWith('image/')) {
        message.error('请选择图片文件',1);
        return;
      }

      // 直接保存File对象
      userInfo.value.avatarFile = file;

      // 创建预览URL
      const reader = new FileReader();
      reader.onload = (e) => {
        previewAvatar.value = e.target.result;
      };
      reader.readAsDataURL(file);
    }
  };
  // 取消编辑的方法
  const cancelEdit = () => {
    if (originalUserInfo.value) {
      userInfo.value = JSON.parse(JSON.stringify(originalUserInfo.value));
      previewAvatar.value = '';
    }
    editMode.value = false;
  };
  // 保存编辑的方法
  const saveEdit = async () => {
    // 验证昵称长度
    validateUsername();
    if (usernameError.value) {
      message.error('昵称长度必须在2-8个字符之间',1);
      return;
    }
    
    try {
      const formData = new FormData();
      formData.append('updateUserRequest', JSON.stringify({
        username: userInfo.value.username,
        sex: userInfo.value.sex,
        occupation: userInfo.value.occupation,
        introduction: userInfo.value.introduction
      }));

      // 如果有新的头像文件，添加到FormData中
      if (userInfo.value.avatarFile) {
        formData.append('avatarFile', userInfo.value.avatarFile);
      }

      // 调用更新接口
      const response = await updateUserInfo(formData);

      // 更新本地用户信息
      const updatedUserInfo = {
        ...userInfo.value,
        avatar: previewAvatar.value || userInfo.value.avatar
      };

      // 更新store中的用户信息
      userStore.setUserInfo(updatedUserInfo);

      // 更新页面显示的用户信息
      userInfo.value = updatedUserInfo;
      originalUserInfo.value = JSON.parse(JSON.stringify(updatedUserInfo));

      // 重置编辑状态
      editMode.value = false;
      userInfo.value.avatarFile = null;
      previewAvatar.value = '';

      message.success('个人信息更新成功',1);

    } catch (error) {
      console.error('保存失败:', error);
      message.error('保存失败，请稍后重试',1);
    }
  };
  // 监听activeMenu变化
  watch(activeMenu, (newVal) => {
    if (newVal === 'content' || newVal === 'analysis') {
      // 延迟初始化图表以确保DOM已更新
      setTimeout(() => {
        initCharts();
        // 添加窗口大小变化监听
        window.addEventListener('resize', handleResize);
      }, 100);
    }
  });
  //图表初始化
  const wordCountChart = ref(null);
  const durationChart = ref(null);
  const resourceChart = ref(null);
  const voiceChart = ref(null);
  const trendChart = ref(null);
  const pieChart = ref(null);
  const barChart = ref(null);
  let contentChartInstances = [];
  let analysisChartInstances = [];

  // 初始化图表
  const initCharts = () => {
    if (activeMenu.value === 'content') {
      try {
        const contentChartConfigs = [
          { ref: wordCountChart.value, config: getWordCountConfig(), delay: 0 },
          { ref: durationChart.value, config: getDurationConfig(), delay: 200 },
          { ref: resourceChart.value, config: getResourceConfig(), delay: 400 },
          { ref: voiceChart.value, config: getVoiceConfig(), delay: 600 }
        ];

        contentChartInstances = contentChartConfigs.map(({ ref, config, delay }) => {
          if (!ref) return null;
          return new Promise(resolve => {
            setTimeout(() => {
              const instance = initChart(ref, config);
              resolve(instance);
            }, delay);
          });
        }).filter(Boolean);

      } catch (error) {
        console.error('图表初始化失败:', error);
      }
    } else if (activeMenu.value === 'analysis') {
      try {
        const analysisChartConfigs = [
          { ref: trendChart.value, config: getTrendConfig(), delay: 0 },
          { ref: pieChart.value, config: getTimeDistributionConfig(), delay: 200 },
          { ref: barChart.value, config: getFunctionUsageConfig(), delay: 400 }
        ];

        analysisChartInstances = analysisChartConfigs.map(({ ref, config, delay }) => {
          if (!ref) return null;
          return new Promise(resolve => {
            setTimeout(() => {
              const instance = initChart(ref, config);
              resolve(instance);
            }, delay);
          });
        }).filter(Boolean);

      } catch (error) {
        console.error('分析图表初始化失败:', error);
      }
    }
  };

  // 处理窗口大小变化
  const handleResize = () => {
    if (activeMenu.value === 'content') {
      contentChartInstances.forEach(chart => chart && chart.resize());
    } else if (activeMenu.value === 'analysis') {
      analysisChartInstances.forEach(chart => chart && chart.resize());
    }
  };

  // 监听activeMenu变化
  watch(activeMenu, (newVal, oldVal) => {
    // 如果离开图表相关的tab，销毁图表实例
    if (oldVal === 'content') {
      contentChartInstances.forEach(chart => {
        if (chart && typeof chart.then === 'function') {
          chart.then(instance => instance && instance.dispose());
        } else if (chart) {
          chart.dispose();
        }
      });
      contentChartInstances = [];
    } else if (oldVal === 'analysis') {
      analysisChartInstances.forEach(chart => {
        if (chart && typeof chart.then === 'function') {
          chart.then(instance => instance && instance.dispose());
        } else if (chart) {
          chart.dispose();
        }
      });
      analysisChartInstances = [];
    }

    // 如果进入图表相关的tab，初始化图表
    if (newVal === 'content' || newVal === 'analysis') {
      // 延迟初始化图表以确保DOM已更新
      nextTick(() => {
        initCharts();
        window.addEventListener('resize', handleResize);
      });
    }
  });

  onMounted(async() => {
    try {
      const response = await getUserInfo();
      if (response.data) {
        userInfo.value = response.data;
        userStore.setUserInfo(response.data);
        originalUserInfo.value = JSON.parse(JSON.stringify(userInfo.value));
        message.success(`欢迎回来，${userInfo.value.username}！`, 1);
      }
      
      // 如果当前在图表页面，初始化图表
      if (activeMenu.value === 'content' || activeMenu.value === 'analysis') {
        initCharts();
        window.addEventListener('resize', handleResize);
      }
    } catch (error) {
      console.error('加载信息失败:', error);
      message.error('加载信息失败，请稍后重试',1);
    }
  });

  onUnmounted(() => {
    window.removeEventListener('resize', handleResize);
    // 销毁图表实例
    const disposeCharts = async () => {
      const allCharts = [...contentChartInstances, ...analysisChartInstances];
      for (const chart of allCharts) {
        try {
          if (chart instanceof Promise) {
            const instance = await chart;
            instance && instance.dispose();
          } else if (chart && typeof chart.dispose === 'function') {
            chart.dispose();
          }
        } catch (error) {
          console.error('销毁图表实例时出错:', error);
        }
      }
    };
    disposeCharts();
    contentChartInstances = [];
    analysisChartInstances = [];
  });


  //账号设置模块
  const passwordForm = ref({
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  });
  const savePassword = async () => {
    // 密码校验
    if (!passwordForm.value.oldPassword) {
      message.error('请输入当前密码',1);
      return;
    }
    if (!passwordForm.value.newPassword) {
      message.error('请输入新密码',1);
      return;
    }
    if (!passwordForm.value.confirmPassword) {
      message.error('请确认新密码',1);
      return;
    }
    if (passwordForm.value.newPassword !== passwordForm.value.confirmPassword) {
      message.error('两次输入的密码不一致',1);
      return;
    }
    // 检查密码长度和复杂度
    const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$/;
    if (!passwordRegex.test(passwordForm.value.newPassword)) {
      message.error('新密码必须包含大小写字母和数字，且长度不少于8位',1);
      return;
    }
    try {
      await updatePassword(passwordForm.value);
      message.success('密码修改成功',1);
      // 清空表单
      passwordForm.value = {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      };
    } catch (error) {
      message.error('密码修改失败，请检查当前密码是否正确',1);
    }
  };
  // 手机号更换相关
  const showPhoneModal = ref(false);
  const phoneForm = ref({
    oldPhone: '138****8888',
    newPhone: '',
    code: ''
  });
  const countdown = ref(0);

  const handleChangePhone = () => {
    showPhoneModal.value = true;
  };

  const sendVerificationCode = async () => {
    if (countdown.value > 0) return;
    // TODO: 调用发送验证码接口
    countdown.value = 60;
    const timer = setInterval(() => {
      countdown.value--;
      if (countdown.value <= 0) {
        clearInterval(timer);
      }
    }, 1000);
  };

  const submitPhoneChange = async () => {
    // TODO: 调用更换手机号接口
    showPhoneModal.value = false;
    // 重置表单
    phoneForm.value.newPhone = '';
    phoneForm.value.code = '';
  };

  //数据中心部分
  const menuGroups = [
    {
      title: '个人信息管理',
      items: [
        { key: 'profile', label: '个人资料' },
        { key: 'settings', label: '账号设置' }
      ]
    },
    {
      title: '数据分析中心',
      items: [
        { key: 'analysis', label: '活动统计' },
        { key: 'content', label: '内容分布' }
      ]
    },
    {
      title: '系统相关',
      items: [
        { key: 'help', label: '使用帮助' },
        { key: 'logout', label: '退出登录', type: 'danger' }
      ]
    }
  ];
  const statistics = ref([
    {
      label: '本周活动次数',
      numericValue: 275,
      unit: '次',
      growth: 15.8
    },
    {
      label: '功能使用总量',
      numericValue: 643,
      unit: '次',
      growth: 18.5
    },
    {
      label: '平均使用时长',
      numericValue: 45,
      unit: '分钟/天',
      growth: 10.2
    }
  ]);

  // 数字动画效果
  const animatedValues = ref(statistics.value.map(() => 0));
  const animatedGrowth = ref(statistics.value.map(() => 0));

  const startAnimation = () => {
    statistics.value.forEach((stat, index) => {
      const startValue = 0;
      const endValue = stat.numericValue;
      const startGrowth = 0;
      const endGrowth = stat.growth;
      const duration = 800;
      const startTime = Date.now();

      const animate = () => {
        const currentTime = Date.now();
        const elapsed = currentTime - startTime;

        if (elapsed < duration) {
          const progress = elapsed / duration;
          animatedValues.value[index] = Math.round(startValue + (endValue - startValue) * progress);
          animatedGrowth.value[index] = (startGrowth + (endGrowth - startGrowth) * progress).toFixed(1);
          requestAnimationFrame(animate);
        } else {
          animatedValues.value[index] = endValue;
          animatedGrowth.value[index] = endGrowth;
        }
      };

      animate();
    });
  };

  watch(activeMenu, () => {
    if (activeMenu.value === 'analysis') {
      nextTick(() => {
        startAnimation();
      });
    }
  });
  // 使用帮助部分
  const helpFeatures = ref([
    {
      icon: SoundOutlined,
      title: '语音库',
      description: '提供丰富多样的语音资源，支持多种音色和语言的语音合成,包括使用系统声音和用户自定义声音。',
      steps: [
        '可以浏览语音库中系统声音的资源列表或者上传自己的自定义的语音',
        '支持删除不需要的语音资源',
        '试听不同音色示例',
        '选择合适的语音音色',
        '应用到文本合成中'
      ],
      faqs: [
        {
          question: '支持哪些语音音色？',
          answer: '目前支持多种男声、女声和童声，包括不同语言和风格的音色选择'
        },
        {
          question: '如何预览音色效果？',
          answer: '可以通过试听按钮收听每个音色的示例，帮助选择最适合的音色'
        }
      ],
      activeKeys: []
    },
    {
      icon: AudioOutlined,
      title: '语音合成',
      description: '提供文本转语音和个性化语音讲解功能，支持多种音色和语言，可上传文件进行转换。',
      steps: [
        '选择转换模式：文本输入或文件上传',
        '文本模式：直接输入或粘贴需要转换的文本',
        '文件模式：上传TXT格式的文档',
        '选择合适的音色、语速参数和输出格式',
        '点击"生成语音"按钮进行转换',
        '等待合成完成后可预览、下载'
      ],
      faqs: [
        {
          question: '支持上传哪些文件格式？',
          answer: '支持TXT、DOC、DOCX、PDF等常见文档格式，单个文件大小不超过10MB'
        },
        {
          question: '如何选择合适的音色？',
          answer: '系统提供多种预设音色，包括男声、女声和童声，可试听后选择；同时支持个性化调整语速、音调等参数'
        },
      ],
      activeKeys: []
    },

    {
      icon: FileTextOutlined,
      title: '课件制作',
      description: '提供智能课件制作功能，支持直接生成和自定义生成两种方式，可根据文本内容自动生成精美的有声课件。',
      steps: [
        '选择课件生成方式：直接生成或自定义生成',
        '上传课件内容：支持文本输入或文件上传',
        '预览和编辑：查看生成效果并进行微调',
        '导出课件：支持课件导出和在线分享'
      ],
      faqs: [
        {
          question: '直接生成和自定义生成有什么区别？',
          answer: '直接生成使用智能算法快速生成标准课件，适合简单场景；自定义生成允许用户调整模板、风格和细节，适合个性化需求'
        },
        {
          question: '支持哪些课件格式？',
          answer: '支持生成PPT、PDF等常见课件格式，可根据需要选择合适的输出格式'
        },
      ],
      activeKeys: []
    },
    {
      icon: UserOutlined,
      title: '账号管理',
      description: '管理个人账号信息，包括基本资料和安全设置。',
      steps: [
        '进入个人中心来修改相关基本信息',
        '进入账号设置修改密码，保存更新',
        '进入数据分析中心查看活动统计、行为分析和内容分布等数据',
        '可以通过图表和数据指标了解使用情况和趋势分析'
      ],
      faqs: [
        {
          question: '如何修改密码？',
          answer: '在账号设置中可以修改登录密码'
        },
        {
          question: '如何查看数据分析？',
          answer: '在数据分析中心可以查看活动统计、行为分析和内容分布等数据，通过图表直观展示使用情况'
        },
      ],
      activeKeys: []
    },
  ]);
  // 处理问题展开/收起
  const handleQuestionClick = (featureIndex, questionIndex, checked) => {
    const feature = helpFeatures.value[featureIndex];
    if (!feature.activeKeys) {
      feature.activeKeys = [];
    }

    if (checked) {
      // 展开问题
      feature.activeKeys.push(questionIndex);
    } else {
      // 收起问题
      const activeKeyIndex = feature.activeKeys.indexOf(questionIndex);
      if (activeKeyIndex !== -1) {
        feature.activeKeys.splice(activeKeyIndex, 1);
      }
    }
  };
  // 退出登录部分
  const handleMenuClick = (key) => {
    if (key === 'logout') {
      Modal.confirm({
        title: '确认退出',
        content: '确定要退出登录吗？',
        okText: '确定',
        cancelText: '取消',
        style: { top: '300px' },
        // zIndex: 1000,
        onOk() {
          userStore.clearUserData();
          router.push('/login');
          message.success('退出成功！',1);
        }
      });
    } else {
      activeMenu.value = key;
    }
  };
  //认证部分
  const showVerifyModal = ref(false);
  const verifyForm = ref({
    realName: '',
    idNumber: '',
    phone: '',
    description: ''
  });

  const handleVerify = () => {
    showVerifyModal.value = true;
  };

  const submitVerify = async () => {
    try {
      // TODO: 调用认证接口
      userInfo.value.isVerified = true;
      userInfo.value.verifyTime = new Date().toLocaleDateString();
      userInfo.value.verifyPurpose = verifyForm.value.description || '个人使用';
      showVerifyModal.value = false;
      message.success('认证提交成功，请等待审核',1);
    } catch (error) {
      console.error('认证提交失败:', error);
      message.error('认证提交失败，请稍后重试',1);
    }
  };

  // 确认密码的校验函数
  const validateConfirmPassword = async (rule, value) => {
    if (value === '') {
      return Promise.reject('请再次输入新密码');
    } else if (value !== passwordForm.value.newPassword) {
      return Promise.reject('两次输入的密码不一致');
    } else {
      return Promise.resolve();
    }
  };
</script>
<style lang="scss" scoped>
.input-wrapper {
  position: relative;
  width: 100%;

  .tooltip {
    position: absolute;
    /* right: -220px; */
    left:36%;
    top: 50%;
    transform: translateY(-50%);
    background-color: #f5f5f5;
    padding: 8px 12px;
    border-radius: 4px;
    font-size: 14px;
    color: #666;
    white-space: nowrap;
    opacity: 0;
    transition: opacity 0.3s;
    pointer-events: none;
    z-index: 1;
    
    &::before {
      content: '';
      position: absolute;
      left: -6px;
      top: 50%;
      transform: translateY(-50%);
      border-width: 6px;
      border-style: solid;
      border-color: transparent #f5f5f5 transparent transparent;
    }
    
    &.show {
      opacity: 1;
    }
    
    &.error {
      background-color: #fff2f0;
      color: #ff4d4f;
      
      &::before {
        border-right-color: #fff2f0;
      }
    }
  }
}
  /* // 全局容器 */
  .container {
    min-height: 100vh;
    background-color: #f9fafb;
    /* max-width: 90rem;
    margin: 0 auto;
    padding: 2rem;
    box-sizing: border-box; */
  }

  /* // 顶部导航 */
  .header {
    height: 60px;
    background-color: white;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
    position: fixed;
    width: 100%;
    top: 0;
    z-index: 50;

    &-content {
      max-width: 1640px;
      margin: 0 auto;
      padding: 0 24px;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    &-left {
      display: flex;
      align-items: center;
      gap: 25px;
      margin-left: 85px;

      img {
        width: 60px;
        height: 30px;
        border-radius: 8px;
      }


      h1 {
        font-size: 22px;
        font-weight: 600;
        background: linear-gradient(45deg, #2563eb, #3b82f6);
        -webkit-background-clip: text;
        background-clip: text;
        color: transparent;
        letter-spacing: 0.05em;
        text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
        font-family: "PingFang SC", "Microsoft YaHei", sans-serif;

      }
    }

    &-right {
      display: flex;
      align-items: center;
      gap: 24px;
      margin-left: 50px;

      .return-btn {
        border-radius: 10px;
        padding: 8px 16px;
        background-color: #3b82f6;
        color: white;
        border: none;
        cursor: pointer;
        white-space: nowrap;

        &:hover {
          background-color: #2563eb;
        }
      }

      .avatar {
        position: relative;
        cursor: pointer;
        display: flex;
        align-items: center;
        gap: 12px;

        img {
          width: 36px;
          height: 36px;
          border-radius: 50%;
        }

        span {
          font-size: 15px;
          font-weight: 500;
          color: #374151;
        }
      }
    }
  }

  /* // 主体内容 */
  .main-content {
    padding-top: 64px;
    display: flex;
    max-width: 90rem;
    margin: 0 auto;
    min-height: 1024px;
  }

  /* // 侧边栏 */
  .sidebar {
    width: 240px;
    background-color: white;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
    position: fixed;
    height: calc(100vh - 64px);
    border-right: 1px solid #f3f4f6;

    &-content {
      padding: 20px 16px;
    }
  }

  /* // 菜单组 */
  .menu-group {
    margin-bottom: 28px;

    .menu-title {
      color: #6b7280;
      margin-bottom: 12px;
      padding: 0 16px;
      font-size: 13px;
      text-transform: uppercase;
      letter-spacing: 0.05em;
      font-weight: 600;
    }

    .menu-item {
      padding: 10px 16px;
      border-radius: 8px;
      font-size: 14px;
      font-weight: 500;
      margin-bottom: 4px;
      transition: all 0.2s ease-in-out;
      cursor: pointer;
      transition: all 0.2s ease-in-out;
      color: #4b5563;
      display: flex;
      align-items: center;

      &:hover {
        background-color: #f3f4f6;
        color: #2563eb;
        transform: translateX(4px);
      }

      &-active {
        background-color: #eff6ff;
        color: #2563eb;
        font-weight: 600;
      }

      &-danger {
        color: #ef4444;

        &:hover {
          background-color: #fef2f2;
          color: #dc2626;
        }
      }

      &-danger {
        color: #ef4444;

        &:hover {
          background-color: #fef2f2;
        }
      }
    }
  }

  .main-area {
    flex: 1;
    margin-left: 240px;
    padding: 32px 40px;
    background-color: #f9fafb;
    min-height: calc(100vh - 64px);
  }

  /* 个人资料部分 */
  .profile-section {
    width: 80%;
    margin: 0 auto;

    .profile-card {
      position: relative;
      background-color: white;
      border-radius: 12px;
      padding: 24px;
      margin-bottom: 24px;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

      .profile-header {
        display: flex;
        gap: 32px;
        margin-bottom: 24px;
        align-items: center;
        height: 250px;
        padding: 6px;
        box-sizing: border-box;

        .avatar-container {
          position: relative;

          &.editable {
            cursor: pointer;
          }

          .avatar-overlay {
            position: absolute;
            inset: 0;
            border-radius: 50%;
            background-color: rgba(0, 0, 0, 0.5);
            display: flex;
            align-items: center;
            justify-content: center;
            opacity: 0;
            transition: opacity 0.3s;

            &:hover {
              opacity: 1;
            }

            .camera-icon {
              color: white;
              font-size: 24px;
            }
          }
        }

        .profile-info {
          flex: 1;

          .profile-title {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 20px;



            .edit-controls {
              display: flex;
              align-items: center;
              gap: 12px;

              .edit-icon {
                font-size: 20px;
                color: #6b7280;
                cursor: pointer;
                transition: color 0.3s;

                &:hover {
                  color: #3b82f6;
                }
              }

              .cancel-btn {
                background-color: #ecedf0;
                color: #374151;

                &:hover {
                  color: #374151;
                  background-color: #d0d2d8;
                }
              }

              .save-btn {
                background-color: #3b82f6;
                border-color: #3b82f6;

                &:hover {
                  background-color: #2563eb;
                  border-color: #2563eb;
                }
              }
            }
          }

          .profile-form {
            .form-item {
              display: flex;
              align-items: center;
              margin-bottom: 16px;

              .form-label {
                width: 80px;
                color: #6b7280;
              }

              :deep(.ant-input),
              :deep(.ant-select) {
                width: 200px;
              }

              &.bio-item {
                align-items: flex-start;

                .bio-input {
                  width: 300px;
                }
              }
            }
          }
        }
      }

      .section-title {
        font-size: 18px;
        font-weight: 600;
        color: #111827;
        margin-bottom: 20px;
      }

      .contact-info {
        display: flex;
        align-items: center;
        gap: 16px;

        .form-label {
          color: #6b7280;
          width: 80px;
        }

        .change-phone-btn {
          padding: 4px 12px;
          border: 1px solid #3b82f6;
          color: #3b82f6;
          background: none;
          border-radius: 4px;
          cursor: pointer;

          &:hover {
            background-color: #eff6ff;
          }
        }
      }

      .auth-info {
        padding: 20px;

        .auth-status {
          display: flex;
          align-items: center;
          margin-bottom: 20px;

          .status-tag {
            margin-left: 10px;
            padding: 4px 12px;
            border-radius: 12px;
            font-size: 14px;

            &.verified {
              background-color: #e6f7ff;
              color: #1890ff;
            }

            &.unverified {
              background-color: #fff1f0;
              color: #ff4d4f;
            }
          }
        }

        .verify-btn {
          width: 100%;
          height: 40px;
          background-color: #1890ff;
          color: white;
          border: none;
          border-radius: 4px;
          cursor: pointer;
          font-size: 14px;
          transition: all 0.3s;

          &:hover {
            background-color: #40a9ff;
          }
        }

        .verify-info {
          margin-top: 16px;

          .info-item {
            display: flex;
            margin-bottom: 12px;

            .info-label {
              color: #666;
              width: 80px;
            }
          }
        }
      }

      .sectionTitle {
        position: absolute;
        font-size: 18px;
        font-weight: 600;
        color: #111827;
        margin-bottom: 20px;
      }
    }
  }

  /* 安全设置部分 */
  .security-section {
    width: 80%;
    margin: 0 auto;

    .security-card {
      background-color: white;
      border-radius: 12px;
      padding: 24px;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

      .section-title {
        font-size: 18px;
        font-weight: 600;
        color: #111827;
        margin-bottom: 24px;
      }

      .save-btn {
        padding: 8px 24px;
        background-color: #3b82f6;
        color: white;
        border: none;
        border-radius: 4px;
        cursor: pointer;

        &:hover {
          background-color: #2563eb;
        }
      }
    }
  }

  /* 数据分析部分 */
  .analysis-section {
    .stats-grid {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 24px;
      margin-bottom: 12px;

      .stat-card {
        background-color: white;
        border-radius: 12px;
        padding: 12px 24px;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

        .stat-label {
          color: #6b7280;
          margin-bottom: 8px;
        }

        .stat-value {
          font-size: 24px;
          font-weight: 600;
          color: #111827;
          margin-bottom: 8px;
        }

        .stat-growth {
          color: #10b981;
          font-size: 14px;
          display: flex;
          align-items: center;
          gap: 4px;
        }
      }
    }

    .chart-card {
      background-color: white;
      border-radius: 12px;
      padding: 24px;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
      margin-bottom: 24px;

      .section-title {
        margin-bottom: 16px;
        color: #111827;
        font-size: 18px;
        font-weight: 600;
      }
    }

    .trend-card {
      margin-bottom: 24px;
    }

    .charts-grid {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 24px;
    }
  }

  .content-section {
    .charts-grid {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 40px;

      .chart-card {
        background: #fff;
        border-radius: 12px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        padding: 20px;
        transition: all 0.3s ease;

        &:hover {
          transform: translateY(-4px);
          box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
        }

        .section-title {
          font-size: 18px;
          font-weight: 600;
          color: #333;
          margin-bottom: 16px;
        }
      }
    }
  }

  /* 使用帮助部分 */
  .help-section {
    width: 90%;
    margin: 0 auto;

    .help-grid {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 24px;
    }

    .help-card {
      background-color: white;
      border-radius: 12px;
      padding: 24px;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
      transition: transform 0.2s;

      &:hover {
        transform: translateY(-4px);
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
      }

      .help-card-header {
        display: flex;
        align-items: center;
        gap: 12px;
        margin-bottom: 20px;

        .feature-icon {
          font-size: 24px;
          color: #3b82f6;
        }

        h3 {
          font-size: 18px;
          font-weight: 600;
          color: #111827;
          margin: 0;
        }
      }

      .help-card-content {
        h4 {
          font-size: 16px;
          font-weight: 500;
          color: #374151;
          margin-bottom: 12px;
        }

        .feature-intro {
          margin-bottom: 20px;

          p {
            color: #6b7280;
            line-height: 1.5;
          }
        }

        .feature-steps {
          margin-bottom: 20px;

          ol {
            padding-left: 20px;
            color: #4b5563;

            li {
              margin-bottom: 8px;
              line-height: 1.5;
            }
          }
        }

        .feature-faq {
          margin-top: 16px;

          :deep(.ant-collapse) {
            border: none;
            background: none;

            .ant-collapse-item {
              border-radius: 8px;
              border: 1px solid #e5e7eb;
              margin-bottom: 12px;
              transition: all 0.3s ease;

              &:hover {
                border-color: #3b82f6;
                box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
              }

              .ant-collapse-header {
                padding: 14px 18px;
                color: #374151;
                font-weight: 500;
                cursor: pointer;
                transition: color 0.3s ease;

                &:hover {
                  color: #3b82f6;
                }
              }

              .ant-collapse-content {
                border-top: 1px solid #e5e7eb;

                .ant-collapse-content-box {
                  padding: 14px 18px;
                  color: #6b7280;
                  line-height: 1.6;
                }
              }
            }
          }
        }
      }
    }
  }

  /* FAQ样式 */
  .faq-collapse {
    background: transparent;
    border: none;

    :deep(.ant-collapse-item) {
      border-radius: 8px;
      margin-bottom: 8px;
      border: 1px solid #e5e7eb;
      overflow: hidden;

      .ant-collapse-header {
        padding: 12px 16px;
        font-weight: 500;
        color: #374151;
        background: #f9fafb;
        transition: all 0.3s ease;

        &:hover {
          background: #f3f4f6;
        }
      }

      .ant-collapse-content {
        border-top: 1px solid #e5e7eb;

        .ant-collapse-content-box {
          padding: 16px;
          background: white;
        }
      }
    }
  }

  .faq-answer {
    color: #4b5563;
    line-height: 1.6;
    margin: 0;
  }
</style>
